import {useEffect, useState} from "react";
import {getAllCateGoryAndTagsUrl} from "@/api/blog/category.ts";
import {getDictUrl} from "@/api/system/dict.ts";


const dictArray: any = [
    {
        key: "status",
        value: [
            {value: 0, label: "正常"},
            {value: 1, label: "停用"}
        ]
    }
]

export function getDict(_key: string) {
    if (_key == null && _key == "") {
        return null;
    }
    try {
        for (let i = 0; i < dictArray.length; i++) {
            if (dictArray[i].key == _key) {
                return dictArray[i].value;
            }
        }
    } catch (e) {
        console.log("getDict", e);
        return null;
    }
}

// 设置字典
export function setDict(_key: string, value: any) {
    if (_key !== null && _key !== "") {
        dictArray.push({
            key: _key,
            value: value
        });
    }
}

// 删除字典
export function removeDict(_key: string) {
    let bln = false;
    try {
        for (let i = 0; i < dictArray.length; i++) {
            if (dictArray[i].key == _key) {
                dictArray.splice(i, 1);
                return true;
            }
        }
    } catch (e: any) {
        console.log("removeDict", e);
        bln = false;
    }
    return bln;
}

// 清空字典
export function clearDict() {
    dictArray.splice(0, dictArray.length);
}


const useGetDict = (...keys: string[]): any => {
    const [result, setResult] = useState({})

    useEffect(() => {
        let resultObject: any = {}
        keys.forEach(async (key) => {
            let value = getDict(key)
            if (!value) {
                // 请求字典 异步获取
                if (key === "art_category") {
                    const re = await getAllCateGoryAndTagsUrl()
                    value = re.data?.cateGory && re.data.cateGory.map((item: any) => {
                        return {
                            value: item.bcId,
                            label: item.bcName
                        }
                    })
                } else if (key === "art_tag") {
                    const re = await getAllCateGoryAndTagsUrl()
                    value = re.data?.tags && re.data.tags.map((item: any) => {
                        return {
                            value: item.btId,
                            label: item.btName
                        }
                    })
                } else {
                    const r = await getDictUrl(key)
                    value = r.data || []
                }
                setDict(key, value)
            }
            resultObject = {
                ...resultObject,
                [key]: value
            }
            setResult(resultObject)
        })
    }, []);

    return result
}

export default useGetDict
